package graphdao

import (
	"power/core/dao/table"
	"power/core/localwrap"
	"power/core/service/common"
	"power/core/service/graph"
	"reflect"

	"strconv"

	"github.com/RocksonZeta/wrap/redised"
	"github.com/RocksonZeta/wrap/utils/sutil"
	"github.com/RocksonZeta/wrap/utils/timeutil"
)

var log = localwrap.GetLogger().WithPkg(reflect.TypeOf(Graphs{}).PkgPath())

const tableGraph = "Graph"

type Graphs struct {
	*redised.RedisedMysql
}

func (s Graphs) redisKey(id int) string {
	return tableGraph + "/" + strconv.Itoa(id)
}

func (s Graphs) ClearCache(id int) {
	s.Redis.Del(s.redisKey(id))
}

type GraphsQueryParam struct {
	common.Page
	Name string
}

//Query 根据条件查询
func (s Graphs) Query(param GraphsQueryParam) ([]table.Graph, int64) {
	wsql := " from Graph where 1=1"
	if param.Name != "" {
		param.Name = "%" + param.Name + "%"
		wsql += " and name like :Name"
	}
	ssql := "select *" + wsql + " order by ct desc" + param.Limit()
	csql := "select count(*)" + wsql
	var r []table.Graph
	s.Mysql.Select(&r, ssql, param)
	return r, s.Mysql.SelectInt(csql, param)
}

func (s Graphs) Get(id int) table.Graph {
	var r table.Graph
	s.RedisedMysql.Get(&r, tableGraph, "Id", id)
	return r
}
func (s Graphs) Get_(id int) graph.Graph {
	var r graph.Graph
	e := s.Get(id)
	r.Graph = e
	r.Props = graph.UnmarshalProps(e.Props)
	return r
}
func (s Graphs) GetByUid(uid int) table.Graph {
	var r table.Graph
	s.RedisedMysql.GetByKvs(&r, tableGraph, "Id", sutil.M{"uid": uid})
	return r
}

func (s Graphs) List(ids []int) []table.Graph {
	var r []table.Graph
	s.RedisedMysql.List(&r, tableGraph, "Id", ids)
	return r
}

func (s Graphs) ListByUid(uid int) []table.Graph {
	var r []table.Graph
	s.RedisedMysql.ListByKvs(&r, tableGraph, "Id", sutil.M{"uid": uid})
	return r
}

type GraphsAddParam struct {
	Name    string
	Creator int
	Props   string
}

func (s Graphs) Add(param GraphsAddParam) table.Graph {
	var t table.Graph
	sutil.Copy(param, &t)
	t.Ct = timeutil.Now()
	if param.Props == "" {
		t.Props = "{}"
	}
	s.Mysql.AddTable(t)
	s.Mysql.Insert(&t)
	s.ClearCache(t.Id)
	return t
}

type GraphsUpdateParam struct {
	Id   int
	Name string
}

func (s Graphs) Update(param GraphsUpdateParam) {
	s.Mysql.Patch(tableGraph, "Id", param)
	s.ClearCache(param.Id)
}
func (s Graphs) UpdateProps(id int, props string) {
	s.Mysql.Patch(tableGraph, "id", sutil.Kv2Map("id", id, "props", props))
	s.ClearCache(id)
}

func (s Graphs) Delete(id int) {
	s.Mysql.Delete(tableGraph, "Id", id)
	s.ClearCache(id)
}
